package main;
// <editor-fold defaultstate="collapsed" desc="import">
import config.ConfigLoader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import tetris.Tetris;
// </editor-fold>
public class Main {
    // <editor-fold defaultstate="collapsed" desc="variable">
    static Socket skt;
    public static String host;
    public static int port;
    BufferedReader in;
    PrintWriter out;
    String username;
    Frame fr;
    Tetris tetris;
    datastream dtst;// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Main()">
    public Main() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        fr = new Frame(this);
        fr.setVisible(true);
        fr.setLocationRelativeTo(null);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="main(String args[])">
    public static void main(String args[]) {
        ConfigLoader configLoader = null;
        try {
            configLoader = ConfigLoader.getInstance("config.cfg");
        } catch (Exception e1) {
            e1.printStackTrace();
            System.err.println("Cannot load config!");
            System.exit(1);
        }
        port = configLoader.getPort();
        host = configLoader.getHost();

        Tetris tetris = new Tetris();
        tetris.setVisible(true);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="login(String user, String pass)">

    public void login(String user, String pass) {
        try {
            skt = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out = new PrintWriter(skt.getOutputStream(), true);
            out.println("1|" + user + "|" + pass);
            String input = in.readLine();
            if (input.equals("1"))//dang nhap thanh cong
            {
                this.username = user;
                fr.loginPanel.removeAll();
                fr.initChoosetypePanel();

            } else if (input.equals("2"))// mat khau or tk khong dung
            {
                //JOptionPane.showMessageDialog(null, "sai mat khau hoac tai khoan");
                fr.ajaxField.setText("Sai username hoặc password!");

            } else if (input.equals("3"))// tai khoan dang duoc su dung
            {
                //JOptionPane.showMessageDialog(null, "tai khoan dang duoc su dung");
                fr.ajaxField.setText("Tài khoản đang được sử dụng!");
            }

        } catch (Exception e) {
            //JOptionPane.showMessageDialog(null, "cannot conect to server! Let Start Server!");
            fr.ajaxField.setText("Không thể kết nối tới server!");
            System.err.println(e);
        }

    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="readMSG(String input) ">

    public void readMSG(String input) {
        char head = input.charAt(0);
        switch (head) {
            case '1':
                tetris.startgame();
                break;
            case '2':
                tetris.deleteuser(input.substring(2));
                break;
            case '3':
                tetris.pausegame();
                break;
            case '4':
                int diem = Integer.parseInt(input.substring(2, 3));
                String username = input.substring(4);
                tetris.denhlen(diem, username);
                break;
            case '5':
                System.out.println("haveUserGameOver");
                tetris.haveusergameover(input.substring(2));
                break;
            case '6':
                tetris.setlistuser(input.substring(2));
                break;
            case '7':
                tetris.recPosition(input.substring(2));
                break;
            case '8':
                tetris.board.GiaiMaChuoiBoard(input.substring(2));
                break;
        }
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="createroom(chooseroom chr) ">

    public void createroom(Frame fr) {
        try {
            skt = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out = new PrintWriter(skt.getOutputStream(), true);
            out.println("8|" + username);
            String input = in.readLine();
            if (input.equals("1")) {
                tetris = new Tetris(this, 1, username);
                tetris.setVisible(true);
                dtst = new datastream(this, in, username);    //in: luôn lắng nghe server1
                fr.dispose();
                //out.println("0");

            } else {
                JOptionPane.showMessageDialog(null, "khong the tao phong game");
            }
        } catch (Exception e) {
            System.out.print("dang loi o createroom Main.java");
            System.err.println(e);
        }

    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="showgame(Frame fr)">

    public void showgame(Frame fr) {
        try {
            skt = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out = new PrintWriter(skt.getOutputStream(), true);
            out.println("7|");
            String input = in.readLine();
            fr.showroomlist(input);
            //System.out.println(input);
            skt.close();
        } catch (Exception e) {
            System.err.println(e);
        }

    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="joingame(String roomname, chooseroom chr)">

    public void joingame(String serverName, Frame fr) {
        try {
            skt = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out = new PrintWriter(skt.getOutputStream(), true);
            out.println("9|" + username + "|" + serverName);
            String input = in.readLine();
            if (input.equals("1")) {
                dtst = new datastream(this, in, serverName);    //in: luôn lắng nghe server2
                tetris = new Tetris(this, 2, username);
                tetris.setVisible(true);
                fr.dispose();
                out.println("0");
                //client2 gửi y/c sendListUser tới server2 
                //server2 y/c SERVER tìm kiếm tất cả serverX nào có cùng serverName với nó

            } else {
                JOptionPane.showMessageDialog(null, "Khong the vao phong");
            }
        } catch (Exception e) {
            System.out.println("loi o ham join game- Main.java");
            System.err.println(e);
        }
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendstartgame()">

    public void sendstartgame() {
        out.println("1");
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendpausegame()">

    public void sendpausegame() {
        out.println("3");
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendghidiem(int diem)">

    public void sendghidiem(int diem) {
        out.println("4|" + diem);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendthoatkhoiphong()">

    public void sendthoatkhoiphong() {
        out.println("6");
    }
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendgameover()">

    public void sendgameover() {
        out.println("5");
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendPosition(String str)">
    public void sendPosition(String str) {
        out.println("7|" + str);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="sendChuoiBoard(String str)">
    public void sendChuoiBoard(String str) {
        out.println("8|" + str);
        System.out.println("client "+username+" da send chuoi board "+str);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="logout()">

    public void logout() {
        try {
            skt = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out = new PrintWriter(skt.getOutputStream(), true);
            out.println("2|" + username);
            System.exit(-1);
        } catch (Exception e) {
            System.err.println(e);
        }
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="singleplayer(Frame lg)">

    public void singleplayer(Frame fr) {

        fr.setVisible(false);
        tetris = new Tetris();
        tetris.board.listUserField.setVisible(false);
        tetris.main = this;
        tetris.username = username;
        tetris.board.listUserField.setText(username);
        tetris.board.loginButton.setText("Logout");
        tetris.setTitle("Tetris-Single");
        tetris.player1.setText(username);
        tetris.getscorefromserver();
        tetris.setVisible(true);
    }// </editor-fold>
}
